﻿#region Copyrigth and License
/*==============================================================================
 *  Copyright (c) cndotnet.org Corporation.  All rights reserved.
 * ===============================================================================
 * This code and information is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the implied warranties
 * of merchantability and fitness for a particular purpose.
 * ===============================================================================
 * Licensed under the GNU General Public License (GPL) v2
 * http://www.cndotnet.org/ezsocio
 * ==============================================================================*/
#endregion
using System;
using System.Web;
using System.Net;
using System.Drawing;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.Collections.Generic;

namespace CNdotnet.Ezsocio.ContactService.QQ {
    /// <summary>
    ///QQContractService 的摘要说明
    /// </summary>
    public class QQService {
        static readonly System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("gb2312");
        private string baseAddress;        
        private string ts;
        private CookieContainer cc;
        public QQService(string ts) {
            cc = new CookieContainer();
            this.ts = ts;            
        }
        public QQService() {
        }
        public string GetTs() {
            string html = Post("http://mail.qq.com", new NameValueCollection());
            string ts = Resove(html, "<input type=\"hidden\" name=\"ts\" value=\"", "\" />");
            return ts;
        }
        public static VerifyCode GetVerifyCode(string sourceUrl, string saveVirtualAddress) {
            VerifyCode vc = new VerifyCode();
            CookieContainer cc = new CookieContainer();
            sourceUrl += Guid.NewGuid().ToString();
            vc.RemoteUrl = sourceUrl;
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(sourceUrl);
            req.CookieContainer = vc.Cookies = cc;
            using (var res = req.GetResponse()) {
                System.Drawing.Image bmp = Bitmap.FromStream(res.GetResponseStream());
                string fn = System.IO.Path.Combine(saveVirtualAddress.TrimEnd('/') + "/", Guid.NewGuid().ToString() + ".bmp");
                string address = HttpContext.Current.Server.MapPath(fn);
                bmp.Save(address);
                vc.ImageUrl = fn;
                return vc;
            }
        }

        public QQContractCollection GetContracts(string uin, string p, string verifycode,string cookies) {
            QQContractCollection qqc = new QQContractCollection();
            NameValueCollection nvc = new NameValueCollection();
            string accept = "image/gif, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-silverlight-2-b2, application/x-silverlight, */*";
            string language = "zh-cn";
            string refer = "http://mail.126.com/";
            string contentType = "application/x-www-form-urlencoded";
            string returnUrl = "";
            string htm = WebOpHelper.GetHtml("http://mail.qq.com", accept, contentType, refer, language, new CookieContainer(), Encoding.GetEncoding("gb2312"), out returnUrl);
            string loginUrl = WebOpHelper.Resove(htm, "<form name=\"form1\" method=\"post\" action=\"", "\"");
            baseAddress = "http://"+new Uri(loginUrl).Host;
            long startTime = (long)((TimeSpan)(DateTime.Now - DateTime.Parse("1970-1-1"))).TotalMilliseconds;
            nvc.Add("aliastype", "@qq.com");
            nvc.Add("delegate_url", "");
            nvc.Add("f", "html");
            nvc.Add("from", "");
            nvc.Add("firstlogin", "false");
            nvc.Add("p", p);
            nvc.Add("pp", "");
            nvc.Add("redirecturl", "");
            nvc.Add("s", "");
            nvc.Add("sid", "0,zh_CN");
            nvc.Add("starttime", startTime.ToString());
            nvc.Add("ts", ts);
            nvc.Add("uin", uin);
            nvc.Add("verifycode", verifycode);
            
            cc.SetCookies(new Uri(loginUrl),cookies);
            string loginPageHtml = Post(loginUrl, nvc);
            nvc = new NameValueCollection();
            string realLoginActionUrl = Resove(loginPageHtml, "location.href=\"", "\"");
            string loginedHtml = Post(realLoginActionUrl, nvc);
            string contractUrl = baseAddress.TrimEnd('/') + Resove(loginedHtml, "<a onFocus=\"this.blur()\" id=\"folder_contact\" href=\"", "\"");
            string contractHTML = Post(contractUrl, nvc);
            string relatedHTML = Resove(contractHTML, "QQ好友", "</ul>");
            List<string> list = ResoveList(relatedHTML, "<li><a href=\"", "</a></li>");
            foreach (string content in list) {
                string[] ssssss = content.Split("\">".ToCharArray());
                if (ssssss.Length == 3) {
                    string groupName = ssssss[2].Substring(0, ssssss[2].LastIndexOf('('));
                    string groupUrl = baseAddress + ssssss[0];
                    string groupHTMl = Post(groupUrl, nvc);
                    List<string> friendList = ResoveList(groupHTMl, "<div class=\"M_l\"", "</div>");
                    foreach (string friendContent in friendList) {
                        string name = Resove(friendContent, "<p class=\"L_n\">&nbsp;", "</p>");
                        string email = Resove(friendContent, "<p class=\"L_e\">", "&nbsp;");
                        string rankStr = Resove(friendContent, "<p class=\"L_r\"><img alt=\"等级：", "\"");
                        int rank = 0;
                        if (!Int32.TryParse(rankStr, out rank)) {
                            rank = 0;
                        }
                        QQContract qq = new QQContract();
                        qq.Rank = rank;
                        qq.Email = email;
                        qq.Name = name;
                        qq.GroupName = groupName;
                        qqc.Add(qq);
                    }
                }
            }
            return qqc;
        }
        private List<string> ResoveList(string html, string prefix, string subfix) {
            List<string> list = new List<string>();
            int index = prefix.Length * -1;
            do {
                index = html.IndexOf(prefix, index + prefix.Length);
                if (index == -1) {
                    break;
                }
                index += prefix.Length;
                int index4 = html.IndexOf(subfix, index);
                string s78 = html.Substring(index, index4 - index);
                list.Add(s78);
            }
            while (index > -1);
            return list;
        }
        private static string Resove(string html, string prefix, string subfix) {
            int inl = html.IndexOf(prefix);
            if (inl == -1) {
                return null;
            }
            inl += prefix.Length;
            int inl2 = html.IndexOf(subfix, inl);
            var s = html.Substring(inl, inl2 - inl);
            return s;
        }
        private string Post(string url, NameValueCollection nvc) {
            StringBuilder sb = new StringBuilder();
            foreach (string key in nvc.AllKeys) {
                sb.Append(key + "=" + HttpUtility.UrlEncode(nvc[key]) + "&");
            }
            HttpWebRequest wc = (HttpWebRequest)HttpWebRequest.Create(url);
            wc.CookieContainer = cc;
            if (!string.IsNullOrEmpty(sb.ToString())) {
                wc.Accept = "image/gif, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-silverlight-2-b2, application/x-silverlight, */*";
                wc.ContentType = "application/x-www-form-urlencoded";
                wc.Referer = "http://mail.qq.com/";
                wc.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";
                wc.Headers.Add("Accept-Language", "zh-cn");
                wc.Headers.Add("UA-CPU", "x86");
                wc.AllowAutoRedirect = true;
                wc.Method = "POST";
                string postData = sb.ToString().TrimEnd('&');
                byte[] postBuffer = encoding.GetBytes(postData);
                wc.ContentLength = postBuffer.Length;
                using (var stream = wc.GetRequestStream()) {
                    stream.Write(postBuffer, 0, postBuffer.Length);
                    stream.Flush();
                    stream.Close();
                }
            }
            using (var res = (HttpWebResponse)wc.GetResponse()) {
                var response = res.GetResponseStream();
                if (wc.CookieContainer != null) {
                    res.Cookies = wc.CookieContainer.GetCookies(wc.RequestUri);
                }
                string responseUrl = res.ResponseUri.ToString();
                StreamReader sr = new StreamReader(response, encoding);
                string c = sr.ReadToEnd();
                Console.WriteLine(c);
                return c;
            }
        }
    }
}